package com.hxzy.dao.Impl;

import com.hxzy.bean.Message;
import com.hxzy.bean.User;
import com.hxzy.dao.MessageDao;
import com.hxzy.service.Impl.UserServiceImpl;
import com.hxzy.service.UserService;
import com.hxzy.util.CommonUtil;
import com.hxzy.util.JdbcUtils;
import com.hxzy.vo.MessageVo;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

public class MessageDaoImpl implements MessageDao {
    @Override
    public int save(Message m) {
        String sql="INSERT INTO message (topic,content,mes_date,author_id ) VALUES (?,?,?,?)";
        Object[] params={m.getTopic(),m.getContent(),m.getMesDate(),m.getUser().getId()};
        return JdbcUtils.executeUpdate(sql,params);
    }

    @Override
    public int update(Message message) {
        return 0;
    }

    @Override
    public int remove(Integer integer) {
        return 0;
    }

    @Override
    public List<Message> queryAll() {
        String sql="SELECT id,topic,content,mes_date mesDate,author_id authorId FROM message order by mes_date desc";
        List<Map<String, Object>> list = JdbcUtils.executeQuery(sql);
        return list.stream().map(t ->getMessage(t)).collect(Collectors.toList());
    }

    @Override
    public Message findById(Integer integer) {
        String sql="SELECT id,topic,content,mes_date mesDate,author_id authorId FROM message WHERE id=?";
        List<Map<String, Object>> list = JdbcUtils.executeQuery(sql,integer);
        Optional<Message> first = list.stream().map(t -> getMessage(t)).findFirst();
        return first.orElse(null);
    }

    private Message getMessage(Map<String, Object> t) {
        int id = ((Long) (t.get("id"))).intValue();
        String topic = (String) t.get("topic");
        String content = (String) t.get("content");
        Timestamp mesDate = (Timestamp) t.get("mesDate");
        LocalDateTime localDateTime = mesDate.toLocalDateTime();
        int authorId = ((Long) (t.get("authorId"))).intValue();
        UserService service = new UserServiceImpl();
        User byId = service.findById(authorId);
        return new Message(id, topic, content, localDateTime, byId);
    }


}
